﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using PHMEE.Admin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PHMEE.MqttClient.Workers
{
    /// <summary>
    /// 心跳检测数采器是否在线，并且获取传感器
    /// </summary>
    public class HeartbeatMonitorService : BackgroundService
    {
        private IDtSendTopicService _dtSendTopicService;
        private ISysParaRepository _sysParaRepository;
        public HeartbeatMonitorService(IDtSendTopicService dtSendTopicService, ISysParaRepository sysParaRepository)
        {
            _dtSendTopicService = dtSendTopicService;
            _sysParaRepository = sysParaRepository;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken);
            while (!stoppingToken.IsCancellationRequested)
            {
                // 获取所有采集器编码
                var collectCodes = await _sysParaRepository.GetAllCollectCodesAsync();

                if (collectCodes.Count > 0)
                {
                    // 离线的数采器编号集合
                    var failedCollectors = await _dtSendTopicService.CheckDataAsync(collectCodes);

                    if (failedCollectors.Count > 0)
                    {
                        // 更新离线状态
                        foreach (var failedCode in failedCollectors)
                        {
                            await _sysParaRepository.UpdataOnlineStatueAsync(failedCode, false); // 标记为离线
                        }
                    }
                }

                // 每30分钟执行一次
                await Task.Delay(TimeSpan.FromMinutes(30), stoppingToken);
            }
        }
    }
}
